<?php

class UsersController extends Controller
{
	public function filters() {
		return array(
			array('application.filters.isAuthorizedFilter'),
			array('application.filters.accessControlFilter - changePassword','roles'=>array(Users::ADMIN_ROLE,Users::MANAGER_ROLE)),
			array('application.filters.accessControlFilter + changePassword','roles'=>array(Users::MANAGER_ROLE,Users::OPERATOR_ROLE)),
		);
	}

	public function actionList()
	{
		$model = new Users('search');
		$model->unsetAttributes();
		if(isset($_GET['Users'])){
			$model->attributes=$_GET['Users'];
		}
		$this->render('list', array(
			'model'=>$model,
		));
	}

	public function actionAdd($id=null)
	{
		if($id){
			$model = Users::model()->findByPk($id);
			if($model === null or (Yii::app()->user->getState('organization_id') != $model->organization_id and Yii::app()->user->getState('role')==Users::MANAGER_ROLE))
				$this->redirect(Yii::app()->createUrl('users/list'));
		} else {
			$model = new Users();
		}

		if(isset($_POST['Users'])){
			$model->attributes = Yii::app()->input->stripClean($_POST['Users']);
			$model->role = Yii::app()->user->getState('role')==Users::MANAGER_ROLE?Users::OPERATOR_ROLE:$model->role;
			$model->organization_id = Yii::app()->user->getState('role')==Users::MANAGER_ROLE?Yii::app()->user->getState('organization_id'):$model->organization_id;
			$model->shop_id = $model->role==Users::MANAGER_ROLE?null:$model->shop_id;

			if($model->save())
				$this->redirect(Yii::app()->createUrl('users/list'));
		}

		$this->render('add',array('model'=>$model));
	}

	public function actionRemove($id)
	{
		$user = Users::model()->findByPk($id);
		if($user !== null or (Yii::app()->user->getState('organization_id') != $user->organization_id and Yii::app()->user->getState('role')==Users::MANAGER_ROLE)){
			$user->active = $user->active?0:1;
			$user->save();
		}

		$this->redirect(Yii::app()->createUrl('users/list'));
	}

	public function actionResetPass()
	{
		$id = Yii::app()->getRequest()->getParam('id');
		$user = Users::model()->findByPk($id);
		if($user !== null and ($user->organization_id == Yii::app()->user->getState('organization_id') or Yii::app()->user->getState('role')==Users::ADMIN_ROLE)){
			$new_pass = substr(md5(time()), 0, 6);
			$user->password = md5(Users::SALT.$new_pass);
			if($user->save()){
				echo '<p>Новый пароль пользователя '.$user->login.': <strong>'.$new_pass.'</strong></p>';
			}
		} else {
			echo '<p>Произошла ошибка.</p>';
		}
	}

	public function actionChangePassword()
	{
		$model = new PasswordForm();

		if(isset($_POST['PasswordForm'])){
			$model->attributes = Yii::app()->input->stripClean($_POST['PasswordForm']);
			if($model->validate()){
				$user = Users::model()->findByPk(Yii::app()->user->id);
				$user->password = md5(Users::SALT.$model->new_password);
				if($user->save()){
					$this->redirect(Yii::app()->user->getReturnUrl());
				}
			}
		}

		$this->render('change_password',array('model'=>$model));
	}
}